package com.hu.zhcc.shiro.controller;

import com.github.pagehelper.PageInfo;
import com.hu.zhcc.shiro.entity.bo.CheckGroup;
import com.hu.zhcc.shiro.entity.bo.CheckItem;
import com.hu.zhcc.shiro.entity.bo.Setmeal;
import com.hu.zhcc.shiro.entity.vo.CheckGroupVO;
import com.hu.zhcc.shiro.entity.vo.SetmealVO;
import com.hu.zhcc.shiro.service.CheckGroupService;
import com.hu.zhcc.shiro.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @GetMapping("")
    public PageInfo<Setmeal> homeSetmeal(SetmealVO setmealVO){
        PageInfo<Setmeal> byCondition = setmealService.findByCondition(setmealVO);
        return byCondition;
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> removeSetmeal(@PathVariable("id") int id) {
        return setmealService.delete(id) > 0 ? ResponseEntity.noContent().build() :
                ResponseEntity.notFound().build();
    }

    @PostMapping("")
    public ResponseEntity<?> saveSetmeal(@RequestBody Setmeal setmeal) {
        List<CheckGroup> checkGroups = setmeal.getCheckGroups();
        Integer[] checkitemIds=new Integer[checkGroups.size()];
        for (int i=0;i<checkGroups.size();i++) {
            checkitemIds[i] = checkGroups.get(i).getId();
        }
        return setmealService.add(setmeal,checkitemIds) > 0 ? ResponseEntity.noContent().build() :
                ResponseEntity.notFound().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Integer> updateSetmeal(@PathVariable("id") int id, @RequestBody Setmeal setmeal) {
        System.out.println(setmeal);
        List<CheckGroup> checkGroups = setmeal.getCheckGroups();
        Integer[] checkitemIds=new Integer[checkGroups.size()];
        for (int i=0;i<checkGroups.size();i++) {
            checkitemIds[i] = checkGroups.get(i).getId();
        }
        int edit = setmealService.edit(setmeal, checkitemIds);
        return edit == 0 ? ResponseEntity.notFound().build() :
                ResponseEntity.status(HttpStatus.CREATED).body(edit);
    }

    @GetMapping("/all")
    public List<Setmeal> listAllCheckItem() {
        return setmealService.findAll();
    }

    @GetMapping("/{id}")
    public Setmeal getById(@PathVariable("id") int id) {
        return setmealService.selectByPrimaryKey(id);
    }
}
